package com.horrorshallots.horrorshallotsblog2.deepseek.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.horrorshallots.horrorshallotsblog2.deepseek.mapper.DialogueMapper;
import com.horrorshallots.horrorshallotsblog2.deepseek.pojo.DeepSeekRequest;
import com.horrorshallots.horrorshallotsblog2.deepseek.service.DialogueService;
import jakarta.transaction.Transactional;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class DialogueServiceImpl implements DialogueService {

    private static final Logger log = LoggerFactory.getLogger(DialogueServiceImpl.class);
    private final DialogueMapper dialogueMapper;
    private final Gson gson = new Gson();

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    public DialogueServiceImpl(DialogueMapper dialogueMapper) {
        this.dialogueMapper = dialogueMapper;
    }

    @Override
    public String startNewConversation(String systemPrompt) {
        String sessionId = UUID.randomUUID().toString();
        if (StringUtils.hasText(systemPrompt)) {
            DeepSeekRequest.Message systemMessage = DeepSeekRequest.Message.builder()
                    .role("system")
                    .content(systemPrompt)
                    .build();
            dialogueMapper.saveMessage(sessionId, systemMessage);
        }
        return sessionId; // 只返回sessionId字符串
    }

    @Override
    public String continueConversation(String sessionId, String userMessage) throws Exception {
        try {
            // 保存用户消息
            DeepSeekRequest.Message userMsg = DeepSeekRequest.Message.builder()
                    .role("user")
                    .content(userMessage)
                    .build();
            dialogueMapper.saveMessage(sessionId, userMsg);

            // 获取历史消息
            List<DeepSeekRequest.Message> messages = dialogueMapper.getMessagesBySessionId(sessionId);

            // 调用API
            DeepSeekRequest requestBody = DeepSeekRequest.builder()
                    .model("deepseek-chat")
                    .messages(messages)
                    .build();

            HttpResponse<String> response = Unirest.post(apiUrl)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .body(gson.toJson(requestBody))
                    .asString();

            if (!response.isSuccess()) {
                log.error("DeepSeek API调用失败: {} - {}", response.getStatus(), response.getStatusText());
                throw new RuntimeException("API调用失败: " + response.getStatusText());
            }

            // 解析API响应并只保存实际内容
            String aiResponse = response.getBody();
            String content = extractContentFromResponse(aiResponse);

            // 保存AI回复(只保存内容，不是完整JSON)
            DeepSeekRequest.Message aiMessage = DeepSeekRequest.Message.builder()
                    .role("assistant")
                    .content(content)
                    .build();
            dialogueMapper.saveMessage(sessionId, aiMessage);

            return content;
        } catch (UnirestException e) {
            log.error("HTTP请求异常", e);
            throw new RuntimeException("服务调用异常", e);
        }
    }

    @Override
    public List<DeepSeekRequest.Message> getConversationHistory(String sessionId) {
        log.debug("获取会话历史: {}", sessionId);
        return dialogueMapper.getMessagesBySessionId(sessionId);
    }

    @Override
    public String endConversation(String sessionId) {
        int deleted = dialogueMapper.deleteMessagesBySessionId(sessionId);
        log.info("结束会话: {}, 删除{}条消息", sessionId, deleted);
        return "{\"status\": \"conversation ended\", \"deleted\": " + deleted + "}";
    }

    /**
     * 从DeepSeek API响应中提取实际内容
     */
    private String extractContentFromResponse(String jsonResponse) {
        try {
            JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
            return jsonObject.getAsJsonArray("choices")
                    .get(0).getAsJsonObject()
                    .getAsJsonObject("message")
                    .get("content").getAsString();
        } catch (Exception e) {
            log.error("解析API响应失败: {}", jsonResponse, e);
            return "无法解析AI回复";
        }
    }
}